//获取应用实例
const app = getApp()
// 获取云数据库操作示例
const db = wx.cloud.database()
const ydb = wx.cloud.database()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    notInMotto: "请点击以下按钮授权您的信息, 方便我们更好地为您服务.",
    userInfo: {},

  },

  //页面加载函数
  onLoad: function () {
    var that = this
    //如果有用户信息，则将信息置换为页面信息
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    }
  },
  //logInThis
  //登录函数与逻辑判断
 async logInThis() {
    var that = this
    //第一次登录
    if (!that.data.userInfo._openid) {
     await that.getUserProfile()
    }
    //第二次及以上
    if (that.data.userInfo._openid) {
      await that.goToIndex()
    }
  },

  // 用户逻辑上第一次登录
  //获取用户信息的函数，
  async getUserProfile() {
    var that = this
    let res1 =  await wx.getUserProfile({
      desc: "用于完善用户体验",
    })
    console.log("res1")
    console.log(res1)
    if(res1.errMsg=="getUserProfile:ok"){
    let user = res1.userInfo
    // 获取用户openid的云函数
     let openidRes = await  wx.cloud.callFunction({
          name: 'logIn',     
    })
      console.log("openidRes")
      console.log(openidRes)
      // 把获取到的用户openid传给userinfo
      user._openid = openidRes.result.openid
      console.log("user._openid " + user._openid)
      // 将用户信息设置成全局变量
      app.globalData.userInfo = user
      console.log(app.globalData.userInfo)
      // 更新视图层的用户信息
      that.setData({
        userInfo: user,
      })
      // 将用户信息保存至本地
      wx.setStorageSync("userInfo", app.globalData.userInfo)
      console.log("第一次登录获得的用户信息 ")
      console.log(app.globalData.userInfo)
      let final = await that.goToIndex()
  }
  },
  //用户逻辑上第二次及以上登录
  //获取用户openid后的登录
  //拥有用户信息后可跳转至首页的函数
  async goToIndex() {
    let addNew = await wx.cloud.callFunction({
      name: 'addNewUser',
      data: {
        _openid: app.globalData.userInfo._openid,
        name: app.globalData.userInfo.nickName,
        img: app.globalData.userInfo.avatarUrl
      },
    })
    console.log(addNew.result)
    //查询到身份信息并且存入全局变量
    let res = await ydb.collection('user').where({
      _openid: app.globalData.userInfo._openid,
    }).get()
    console.log(res)
    app.globalData.userInfo = res.data[0]
    wx.setStorageSync("userInfo", app.globalData.userInfo)
    console.log("userInfo In Storge")
    console.log(app.globalData.userInfo)
    wx.switchTab({
      url: '../index/index',
      success: function () {
        console.log("jump success")
      },
      fail: function () {
        console.log("jump failed")
      }
    });
  },

})